/**
 * Created by liyl on 08/03/2021.
 */
import { CommonModule } from '@/store/modules/common'
import { storageManager } from 'src/utils/common'
import { LoginModule } from 'src/store/modules/login/index'
import { OemModule } from '@/store/modules/oem'
import routes from './index'
import VueRouter from 'vue-router'
import { PermissionModule } from '@/store/modules/permission'
import './ele/index'
const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})
if (CommonModule && CommonModule.containerType && CommonModule.containerType === 'v7Cloud') { // 只有v7的主应用才走路由守卫钩子
  const loadingPane = document.getElementById('v7_body')
  router.beforeEach(async (to: any, from, next) => { // 刷新
    // next()
    // return false
    if (CommonModule && CommonModule.session && CommonModule.session.user && CommonModule.session.user.loginToken) {
      next()
    } else {
      if (to.path === '/login') {
        OemModule.OemCommonAction().then((res: any) => {
          if (res && res.success) {
            CommonModule.setInitConfig(res.data || {})
          }
          if (loadingPane) {
            loadingPane.className = ''
          }
          next()
        }).catch(() => {
          if (loadingPane) {
            loadingPane.className = ''
          }
          next()
        })
      } else if (to.fullPath === '/') { // 不带/login || 不是/?tokenId=xxxx
        next('/login')
      } else {
        let toPath = to.fullPath
        if (to.query && to.query.sessionId) {
          toPath = '/home'
          window.sessionStorage.setItem('sessionId', to.query.sessionId)
        }
        if (to.query && to.query.tokenId) {
          toPath = '/home'
          window.sessionStorage.setItem('tokenId', to.query.tokenId)
        }
        CommonModule.getNavMenuState() // 从sessionStoreage获取导航的展开收起状态
        const sessionFrom = window.sessionStorage.getItem('sessionForm') // session里存储的登录信息，用于2个座席登录，刷新走各自的信息
        let localForm = sessionFrom || storageManager.get('loginForm')
        const localWebchatStatus = storageManager.get('webchatStatus')
        const localSession = window.sessionStorage.getItem('sessionId')
        const localToken = window.sessionStorage.getItem('tokenId')
        let webchatStatus: any
        if (localWebchatStatus && localWebchatStatus !== 'undefined' && localWebchatStatus !== 'null') {
          webchatStatus = JSON.parse(localWebchatStatus)
        } else {
          webchatStatus = { status: 'open', _id: '' }
        }
        localForm = localForm && localForm !== 'undefined' && localForm !== 'null' ? JSON.parse(localForm) : {}
        if ((!localForm.loginName || !localForm.password) && !localSession && !localToken) { // 没有登录信息 && 不是session登录 && 不是token登录
          next('/login')
        } else {
          OemModule.OemCommonAction().then((res: any) => {
            if (res && res.success) {
              CommonModule.setInitConfig(res.data || {})
            }
            let actionName = 'SignIn'
            let loginData: any = { form: localForm, encrypted: localForm.password, isLogin: false, webchatStatus, isConnectSocket: true, isConnectWebRtc: true }
            if (localSession) { // sessionId登录
              actionName = 'SignInBySessionId'
              loginData = { sessionId: localSession }
            } else if (localToken) { // tokenId登录
              actionName = 'SignInByToken'
              loginData = { ssoToken: localToken }
            }
            LoginModule[actionName](loginData).then((loginRes: any) => {
              if (loginRes && loginRes.success) {
                if (loginRes.data.isRefresh) {
                  localStorage.setItem('refresh', 'yes')
                  location.reload()
                } else {
                  localStorage.setItem('refresh', 'no')
                }
                // 通过菜单权限 生成动态路由
                const commonAppIdList = ['knowledge_mgt', 'call_task', 'robot', 'sms']
                const list = CommonModule.publicCache.commonAppIdList.map((item: any) => item.id) || [] // 常用应用列表
                const roleList = loginRes.data.user.limits
                PermissionModule.GenerateRoutes(roleList)
                // 设置动态路由
                router.addRoutes(PermissionModule.routes)
                commonAppIdList.forEach(item => {
                  if (item === 'call_task' && roleList.includes('call_task')) { // 有预览外呼的权限
                    if (!(list.includes('my_call_task_list') || list.includes('my_auto_call_task_list') || list.includes('auto_call_task_list') || list.includes('preview_dialout_list'))) {
                      // 我的预览外呼 || 我的自动外呼 || 预览外呼管理 || 自动外呼管理  都没有设置为常用，要把一级菜单的外呼任务剔除
                      PermissionModule.delRoutes('call_task')
                      CommonModule.updateLoginMenuList({ menu: 'call_task', type: 'delete' })
                    }
                  } else if (!(roleList.includes(item) && list.includes(item))) {
                    if (roleList.includes(item)) {
                      PermissionModule.delRoutes(item)
                    }
                  }
                })
                if (toPath === '/') {
                  next('/login')
                } else if (to.query && to.query.customRouter) { // 允许客户自定义，要跳转到哪个模块
                  next({ path: `/${to.query.customRouter}`, query: to.query })
                } else if (toPath === '/home') { // 普通登录、token, sessionId登录都走一遍权限根据权限配置，跳转到第一个菜单
                  const firstPath = (CommonModule.publicCache && CommonModule.publicCache.loginMenuList[0]) || 'home'
                  next(`/${firstPath}/index`)
                } else {
                  next(toPath)
                }
              } else {
                next('/login')
              }
            }).catch(() => {
              next('/login')
            })
          }).catch(() => {
            next('/login')
          })
        }
      }
    }
  })
}
export default router
